# coding=utf-8

from scene import Scene
from question import QuestionGroup
# from question import test
from timer import Timer
import pygame
import pygame_gui

# import group1
# import group2
# import group3

WIN_WIDTH = 1600
WIN_HEIGHT = 800

LABEL_HEIGHT = WIN_HEIGHT // 7
ANSWER_HEIGHT = LABEL_HEIGHT
QUESTION_HEIGHT = 2 * LABEL_HEIGHT

#ques_lib = group1.gen_ques(50, swap=True)
#ques_lib = group2.gen_ques(50, category=20)
# ques_lib = group3.gen_ques(50, swap=True)

class SceneTest(Scene):

    def __init__(self):
        super().__init__()
        self.ques_idx = 0
        self.ques_new = True
        self.answ_idx = -1
        self.answ_sel_idx = -1

        self.ques_count = 0
        self.correct_count = 0
        self.wrong_count = 0

        self.timer = Timer()

        # 创建 GUI 管理器
        self.manager = pygame_gui.UIManager((WIN_WIDTH, WIN_HEIGHT), 'theme.json')

        self.label_no = pygame_gui.elements.UILabel(
            relative_rect=pygame.Rect((0, 0), (300, LABEL_HEIGHT)),
            text="第 1 题",
            manager=self.manager,
            object_id=pygame_gui.core.ObjectID(object_id='#label_no')
        )

        self.label_correct = pygame_gui.elements.UILabel(
            relative_rect=pygame.Rect((0, 0), (300, LABEL_HEIGHT)),
            text="正确数：0",
            manager=self.manager,
            object_id=pygame_gui.core.ObjectID(object_id='#label_correct'),
             anchors = {"top": "top",
                        "right": "left",
                        "left_target": self.label_no}
        )

        self.label_wrong = pygame_gui.elements.UILabel(
            relative_rect=pygame.Rect((0, 0), (300, LABEL_HEIGHT)),
            text="错误数：0",
            manager=self.manager,
            object_id=pygame_gui.core.ObjectID(object_id='#label_wrong'),
             anchors = {"top": "top",
                        "right": "left",
                        "left_target": self.label_correct}
        )

        self.label_time = pygame_gui.elements.UILabel(
            relative_rect=pygame.Rect((0, 0), (300, LABEL_HEIGHT)),
            text="时间：00:00",
            manager=self.manager,
            object_id=pygame_gui.core.ObjectID(object_id='#label_time'),
             anchors = {"top": "top",
                        "right": "left",
                        "left_target": self.label_wrong}
        )

        self.timer.set_change_func(lambda x: self.label_time.set_text("时间：%s" % Timer.str_time(x)))

        self.textbox_question = pygame_gui.elements.UITextBox(
            relative_rect=pygame.Rect((0, LABEL_HEIGHT), (WIN_WIDTH, QUESTION_HEIGHT)),
            html_text="时间：00:00",
            manager=self.manager,
            object_id=pygame_gui.core.ObjectID(object_id='#text_box_question'),
            #  anchors = {"top": "top",
            #             "right": "left",
            #             "left_target": label_wrong}
        )

        self.button_answers = []
        for i in range(4):
            button_answer = pygame_gui.elements.UIButton(
                relative_rect=pygame.Rect((0, i*ANSWER_HEIGHT + QUESTION_HEIGHT + LABEL_HEIGHT), (WIN_WIDTH, ANSWER_HEIGHT)),
                text="",
                manager=self.manager,
                object_id=pygame_gui.core.ObjectID(class_id='@button_answer_left' if i % 2 == 0 else '@button_answer_right')
                                                   #object_id='#hello_button')#,
                # object_id=pygame_gui.core.ObjectID(object_id='#label_time'),
                #  anchors = {"top": "top",
                #             "right": "left",
                #             "left_target": label_wrong}
            )
            self.button_answers.append(button_answer)

    def activate(self, params = None):
        # self.ques_lib = ques_lib
        self.ques_idx = 0
        self.ques_new = True
        self.answ_idx = -1
        self.answ_sel_idx = -1

        self.ques_count = 0
        self.correct_count = 0
        self.wrong_count = 0

        assert params
        assert params["question_group"]
        if "question_count" not in params:
            params["question_count"] = 10
        self.question_group = params["question_group"]
        questions = self.question_group.GetQuestions() # shuffle questions
        self.ques_count = min(len(questions), params["question_count"])
        print("params", params)
        self.questions = questions[:self.ques_count]
        self.current_question = self.questions[self.ques_idx]
        self.activate_params = params

        self.timer.start_timer()

        self.label_correct.set_text("正确数：%d" % self.correct_count)
        self.label_wrong.set_text("错误数：%d" % self.wrong_count)

        pygame.display.set_caption("测试： %s" % self.question_group.summary)


    def select_correct(self):
        self.correct_count += 1
        self.label_correct.set_text("正确数：%d" % self.correct_count)
        print("correct!")


    def select_wrong(self):
        self.wrong_count += 1
        self.label_wrong.set_text("错误数：%d" % self.wrong_count)
        print("wrong!")


    def process_events(self, events):
        if self.ques_new:
            if self.ques_idx == len(self.questions):
                params = {
                    "correct_count": self.correct_count,
                    "wrong_count": self.wrong_count,
                    "total_count": self.ques_count,
                    "test_params": self.activate_params,
                }
                return self.switch("test_result", params)


            print("ques_idx = %d, len(ques_lib) = %d" % (self.ques_idx, len(self.questions)))
            # ques = self.ques_lib[self.ques_idx]

            # self.current_question = self.questions[self.ques_idx]
            ques = self.questions[self.ques_idx]

            self.textbox_question.html_text = ques.GetDescription()
            self.textbox_question.rebuild()
            for ans_idx in range(0, 4):
                self.button_answers[ans_idx].set_text(ques.GetOption(ans_idx))
                self.button_answers[ans_idx].enable()

            self.current_question = ques

            # self.answ_idx = ques[5]
            self.ques_idx += 1

            self.label_no.set_text("第 %d/%d 题" % (self.ques_idx, self.ques_count))

            self.ques_new = False

        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    print("A key pressed")
                if event.key == pygame.K_b:
                    print("B key pressed")

            elif event.type == pygame_gui.UI_BUTTON_PRESSED:
                answ_sel_idx = -1
                for i, button_answer in enumerate(self.button_answers):
                    if event.ui_element == button_answer:
                        answ_sel_idx = i
                        break

                assert  answ_sel_idx != -1

                correct = self.current_question.Judge(answ_sel_idx)
                if correct:
                    self.select_correct()
                    self.ques_new = True

                else:
                    button_answer.disable()
                    self.select_wrong()

                        # if answ_sel_idx == self.answ_idx:
                        #     self.select_correct()
                        #     self.ques_new = True
                        # else:
                        #     button_answer.disable()
                        #     self.select_wrong()
                        # break

            self.manager.process_events(event)

        self.timer.tick_timer()


    def update(self, time_delta):
        self.manager.update(time_delta)


    def draw(self, screen):
        self.manager.draw_ui(screen)
